<template>
    <div class="app-container">
        <el-card class="box-card" shadow="always" v-show="showSearch">
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
                <el-form-item label="客户名称" prop="supplierId">
                    <el-select v-model="queryParams.supplierId" filterable clearable remote reserve-keyword
                        placeholder="请选择客户" :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')"
                        :loading="loading" @change="handleQuery">
                        <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="经手人" prop="userId">
                    <el-select v-model="queryParams.userId" filterable clearable remote reserve-keyword
                        placeholder="请选择经手人" :loading="loading" @change="handleQuery">
                        <el-option v-for="item in userList" :key="item.value" :label="item.realityName"
                            :value="item.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="客户区域">
                    <el-select v-model="queryParams.areaId" placeholder="请选择客户区域" @change="handleQuery">
                        <el-option v-for="item in areaList" :key="item.id" :value="item.id"
                            :label="item.areaName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="归属部门" prop="deptId">
                    <el-tree-select v-model="queryParams.deptId" :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                        placeholder="请选择归属部门" check-strictly @change="handleDeptChange" />
                </el-form-item>
                <!-- <el-form-item label="产品分类" prop="classifyId">
                    <el-tree-select :props="{ value: 'id', label: 'classifyName', children: 'children' }"
                        v-model="queryParams.classifyId" :data="categoryList" clearable :render-after-expand="false" />
                </el-form-item> -->
                <!-- 
                <el-form-item label="产品名称" prop="goodsName">
                    <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable
                        @keyup.enter="handleQuery" />
                </el-form-item> -->
                <el-form-item label="录单日期" prop="dateRange">
                    <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" align="right"
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                        :picker-options="pickerOptions" format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="box-card" shadow="always" :body-style="{ padding: '20px' }">
            <template #header>
                <div>
                    <el-row :gutter="10" class="mb8">

                        <el-button type="primary" @click="handleAdd" v-hasPermi="['order:payOrder:add']">添加续费单
                        </el-button>

                        <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                    </el-row>
                </div>
            </template>
            <el-table border show-summary v-loading="loading" :data="dataSource"
                @selection-change="handleSelectionChange" @row-dblclick="handleView" :summary-method="getSummaries">
                <el-table-column type="selection" width="60" align="center" :selectable="selectHandle" />
                <el-table-column label="#" type="index"> </el-table-column>
                <el-table-column label="续费单号" align="center" prop="payOrderCode" />
                <el-table-column label="录单日期" align="center" prop="payOrderDate" />
                <el-table-column label="客户名称" align="center" prop="supplierName" />
                <el-table-column label="归属部门" align="center" prop="deptName" />
                <el-table-column label="联系人" align="center" prop="contacts" />
                <el-table-column label="续费金额" align="center" prop="payAmount" />
                <el-table-column label="经手人" align="center" prop="userName" />
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="操作" align="center" prop="orderStatus" width="250">
                    <template #default="scope">
                        <el-button type="text" @click="handleView(scope.row)"
                            v-hasPermi="['order:payOrder:edit']">查看</el-button>
                        <el-button type="text" @click="handleEdit(scope.row)"
                            v-hasPermi="['order:payOrder:edit']">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope.row.id)"
                            v-hasPermi="['order:payOrder:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page.sync="queryParams.pageNum"
                v-model:limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <statusForm ref="statusForm"></statusForm>
    </div>
</template>

<script>
import request from '@/utils/request'
import api from '@/api/system/user';
import statusForm from './modules/statusForm.vue';
import listMixin from '@/mixins/listMixin';
import useExport from '@/components/PPTist/hooks/useExport'
import { randomUUID } from '@/utils/util'
import { getQuotation } from '@/api/goods/quotation';
const { exportPPTX, exporting } = useExport()
export default {
    name: "PayOrder",
    dicts: ["inventory_status", "counting_method"],
    components: {
        statusForm
    },
    mixins: [listMixin],
    data() {
        return {
            showSearch: true, // Whether to show the search form
            queryParams: { // Query parameters for the table
                pageNum: 1, // Current page number
                pageSize: 10, // Number of records per page
                orderByColumn: 'createTime', // Sorting column
                isAsc: 'desc', // Sorting order
                deptId: ''
            },
            dateRange: [], // Date range for the created time
            loading: false, // Loading state of the table
            dataSource: [], // Data for the table
            total: 0, // Total number of records
            multiple: false, // Whether multiple rows are selected
            categoryList: [],//产品分类
            deptOptions: [], //归属部门
            renewal_time_type: [],
            supplierOptions: [], //客户
            currentRow: {}, // Current row data
            urls: {
                list: '/order/payOrder/list',
                delete: '/order/payOrder',
            }
        };
    },
    mounted() {
        this.getDicts(['renewal_time_type']);
        this.listSysUser();
        this.getTreeSelect(); // 初始化部门数据
        this.getArea();
        this.getSupplierAllList(1)
    },
    methods: {
        ...mapActions('user', ['getInfo']),
        // 查询列表
        getList() {
            this.loading = true;
            this.queryParams.params = { ...this.queryParams.params, ...this.params };
        }
    },
    methods: {
        getQueryParams() {
            let params = Object.assign({}, this.queryParams);
            params.params = { ...this.params };
            if (this.dateRange && this.dateRange.length) {
                params.params['createBeginTime'] = this.dateRange[0] + ' 00:00:00';
                params.params['createEndTime'] = this.dateRange[1] + ' 23:59:59';
            }
            return params;
        },
        remoteMethod(query, listKey, key) {
            const optionKey = listKey + 'Options';
            if (query !== '') {

                this[optionKey] = this[listKey + 'List'].filter(item => {
                    return item[key].toLowerCase()
                        .indexOf(query.toLowerCase()) > -1;
                });
            } else {
                this[optionKey] = this[listKey + 'List'];
            }

        },

        handleStatus(row) {
            console.log('666 :>> ', 666);
            this.$refs.statusForm.edit(row);
        },
        /** 查询部门下拉树结构 */
        async getTreeSelect() {
            const res = await api.deptTreeSelect();
            this.deptOptions = res.data;
        },
        async selectOk(row) {
            const res = await getQuotation(this.currentRow.id)

            const data = {
                goodsName: '商品名称',
                goodsSku: 'SKU',
                itemNo: '货号',
                primarilyImg: '商品默认图片',
                packImg: '商品主图',
                auxiliaryImg: '商品副图',
                goodsUnit: '商品单位',
                goodsSize: '商品尺寸',
                costPrice: '成本价',
                wholesalePrice: '批发价',
                upsetPrice: '最低售价',
                retailPrice: '零售价',
                purchasePrice: '一件代发采购价',
                salePrice: '一件代发销售价',
                supplyMode: '供货方式',
            }
            res.data.quotationItemVoList = res.data.quotationItemVoList//.map(v => (v.jzgGoodsVo = data, v))
            console.log('res.data :>> ', res.data);
            let slides = this.resetSelides(row, res.data)
            exportPPTX(slides, false, false)
        },
        // 计算slides
        /**
         * 
         * @param {*} templateInfo 模板信息
         * @param {*} materialInfo 商品
         */
        resetSelides(templateInfo, materialInfo) {
            // 重置slides
            let newSlides = []
            let defaultSlides = JSON.parse(templateInfo.remark)
            console.log('defaultSlides :>> ', defaultSlides);
            defaultSlides.forEach((slide) => {
                if (!slide.isDynamic) {
                    newSlides.push(slide)
                } else {
                    (materialInfo.quotationItemVoList || []).forEach(val => {
                        newSlides.push({
                            ...slide,
                            id: slide.id + randomUUID(),
                            elements: slide.elements.map((element) => {
                                if (element.keyStr) {
                                    let pattern = />([^<]+)</g
                                    let bodyString = element.content.replace(pattern, `>${val.jzgGoodsVo[element.keyStr]}<`)
                                    return {
                                        ...element,
                                        content: bodyString
                                    }
                                }
                                return element
                            })
                        })
                    });
                }
            })
            return newSlides
        },
        getType(status) {
            switch (status) {
                case '0':
                    return 'primary';
                case '1':
                    return 'success';
                case '2':
                    return 'danger';
                default:
                    return 'info';
            }
        },
        getSummaries(param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计'
                    return
                }
                const values = data.map((item) => Number(item[column.property]))
                const keyArr = ['payAmount', 'goodsAmount', 'goodsNumber']
                if (keyArr.includes(column.property)) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr)
                        if (!Number.isNaN(value)) {
                            return prev + curr
                        } else {
                            return prev
                        }
                    }, 0)
                } else {
                    sums[index] = '-'
                }
            })
            return sums
        },
        handleAdd() {
            this.$router.push({
                name: 'PayOrderAdd',
            })
        },
        handleEdit(row) {
            console.log(row)
            this.$router.push({
                name: 'PayOrderAdd',
                query: {
                    dataList: JSON.stringify(row),
                    type: 'edit'
                }
            })
        },
        handleDelete(ids) {
            this.$modal.confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request({
                    url: this.urls.delete + '/' + ids,
                    method: 'delete'
                }).then(res => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('删除成功')
                        this.getList()
                    }
                }).catch(() => {
                    this.$router.push({
                        name: 'PayOrderDetail',
                        query: {
                            payOrderId: ids
                        }
                    })
                });;
            })
        },
        handleView(row) {
            console.log(row)
            this.$router.push({
                name: 'PayOrderAdd',
                query: {
                    dataList: JSON.stringify(row),
                    type: 'view'
                }
            })
        },
        resetQuery() {
            this.queryParams = {//查询条件
                pageNum: 1,
                pageSize: 10,
                orderByColumn: 'createTime', // Sorting column
                isAsc: 'desc', // Sorting order
                deptId: ''
            }
            this.dateRange = []
            this.getList()
        },
    },
};
</script>
<style type="text/css" scoped>
.box-card {
    margin-bottom: 10px;
}
</style>